var aid = GetQueryString('admin_id') || '';
if(isEmpty(aid)){
    malert("非法操作", function () {
        return false;
    });
}
$("#aid").val(aid);

var _getParam = function (obj, param) {
    console.log(obj[param])
    return obj[param] || '';
};
/*var cityPicker3 = new mui.PopPicker({
    layer: 3
});
cityPicker3.setData(cityData3);
cityPicker3.pickers[0].setSelectedIndex(0);
cityPicker3.pickers[0].setSelectedValue('110000');
cityPicker3.pickers[1].setSelectedIndex(0);
cityPicker3.pickers[1].setSelectedValue('110000');
cityPicker3.pickers[2].setSelectedIndex(0);
cityPicker3.pickers[2].setSelectedValue('110101');
var showCityPickerButton = document.getElementById('showCityPicker3');
//监听重选地址
showCityPickerButton.addEventListener('tap', function (event) {
    cityPicker3.show(function (items) {
        showCityPickerButton.value = _getParam(items[0], 'text') + " " + _getParam(items[1], 'text') + " " + _getParam(items[2], 'text');
        $("#province").val(_getParam(items[0], 'value'));
        $("#city").val(_getParam(items[1], 'value'));
        $("#area").val(_getParam(items[2], 'value'));

    });
}, false);*/

var is_mobile = function(e) {
    var status = true;
    if (!(/^1\d{10}$/.test( $(e).val()))){
        status = false;
    }
    return {
        status: status, // or false
        message: '请填写正确的手机号'
    };
}

$('.form-item').on('tap',function (res) {
    var target = res.currentTarget;
    if(isEmpty(target)){
        return;
    }
    if($(target).hasClass('border_active')){
        return;
    }else {
        $('.form-item').removeClass('border_active');
        $(target).addClass('border_active');
    }

})


var ajaxOption = {
    url: shop_simple,
    method: 'POST',
    data:comParams(),
    success: function (res) {
        setTimeout(function () {
            location.replace('success.html?type=5');
        },2000);
    }
};

checkform($('#myform'), ajaxOption);

var winHeight = $(window).height();   //获取当前页面高度
$(window).resize(function(){
    var thisHeight=$(this).height();
    if(winHeight - thisHeight >50){

        //当软键盘弹出，在这里面操作
        $(".sure-submit").hide();
    }else{
        //当软键盘收起，在此处操作
        $(".sure-submit").show();
    }
});


//点击获取验证码
/*$('.get_code').on('tap', function () {*/
$('#getCode').bind('click',function () {

    $(this).addClass('mui-disabled').attr('disabled', true);
    var mobile = $('.shop_phone').val();
    var verify = $('.verify').val();
    if(isEmpty(verify)) {
        malert('图形码', '提示', '确定');
        $('#get_code').removeClass('mui-disabled').removeAttr('disabled');
        return;
    }
    if (isEmpty(mobile)) {
        malert('请填写联系方式', '提示', '确定');
        $('#get_code').removeClass('mui-disabled').removeAttr('disabled');
        return;
    }
    var success = function (res) {
        console.log(res)
        var info = res.sms_time;

        $('#getCode').text(info + 's');
        var intervarId = null;

        function count_down() {
            info--;
            if (info <= 0) {
                clearInterval(intervarId);
                $('#getCode').removeClass('mui-disabled').removeAttr('disabled');
                $('#getCode').text('请重新获取');
                return;
            }
            $('#getCode').text(info + 's');
        }

        intervarId = setInterval(function () {
            count_down();
        }, 1000);

    }

    getData(simple_sms, combineParams({mobile: mobile,type:3,verify:verify}), success);
})

//监听电话发生改变
shop_phone.addEventListener("change", function(event) {
    var account_name = $('.account_name').val();
    if(isEmpty(account_name)){
        var shop_phone = $('.shop_phone').val();
        $('.account_name').val(shop_phone);
    }
});

//获取图形验证码
$('.verify_img').attr('src',img_captcha);

$('.verify_img').bind('click',function () {
    $('.verify_img').attr('src',img_captcha);
})


//地图相关
//计算地图全屏高度
/*var height = $(document).height();
$('#container').css('height',height);*/
var geocoder, map, circle ,marker ,info ,lat ,lng ,address ,name,center ,nearPost ,shop_center , range_height ,province,city,area = null;
var range = true; //表示配送范围
var area_info = null;
var shop_city=''

geocoder = new qq.maps.Geocoder();

//点击地区页面的搜索
$('.for-search').bind('click',function () {
    $('#map').hide();
    $('#search').show();
    setTimeout("$('#search_address').focus()",100);
})

//点击搜索页面的回退
$('.for-map').bind('click',function () {
    $('#map').show();
    $('#search').hide();
})

//点击地区选地址
$('#area_info').bind('click',function () {
    $('#latLng').show();
    $('#map').show();
    $('#add').hide();
})

$('.toHistory').bind('click',function () {
    $('#latLng').hide();
    $('#search').hide();
    $('#add').show();
})

init();

function init() {

    //获取用户当前地址
    var geolocation = new qq.maps.Geolocation("RHHBZ-K26W6-CPISS-ENGXG-HVCRS-QJFQT", "qds");
    var options = {timeout: 8000};
    geolocation.getLocation(showPosition, showErr, options)
    function showPosition(position) {
        province = position.province;
        city = position.city;
        area = isEmpty(position.district)?'':position.district;

        lat = position.lat;
        lng = position.lng;

        if(!isEmpty(city)){
            region = city;
        }

        //获取该定位附近地址
        codeLatLng(lat,lng);

        //拿到经纬度并定位
        center = new qq.maps.LatLng(lat, lng);
        map = new qq.maps.Map(document.getElementById("container"), {
            center: center,
            zoom: 16,
            zoomControl: false,
        });

        marker = new qq.maps.Marker({
            //设置Marker的位置坐标
            position: center,
            //设置显示Marker的地图
            map: map
        });
        //设置Marker是否可以被拖拽，为true时可拖拽，false时不可拖拽，默认属性为false
        marker.setDraggable(false);

        if(!isEmpty(shop_center) && !isEmpty(range_height) && range_height >0){
            //判断该定位是否在配送范围
            rangeLatLng(center);
        }

        getAddressCode(province,city,area);

        //点击地图获取点击地点的地址和坐标
        geocoder = new qq.maps.Geocoder({
            complete : function(result){
                nearPost = result.detail;
                province = nearPost.addressComponents.province;
                city = nearPost.addressComponents.city;
                area = isEmpty(nearPost.addressComponents.district)?'':nearPost.addressComponents.district;
                getAddressCode(province,city,area);
                //将附近地址渲染到对应位置
                near_addList(nearPost);
            }
        });

        //绑定单击事件添加参数
        qq.maps.event.addListener(map, 'click', function(event) {
            to_addDetail = 0;
            marker.setMap(null);
            //根据获取的经纬度 得到具体地址
            make_map(event.latLng.getLat(),event.latLng.getLng());
            var latLng = new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng());
            geocoder.getAddress(latLng);

            if(!isEmpty(geocoder)){
                //设置服务请求成功的回调函数
                geocoder.setComplete(function(result) {
                    nearPost = result.detail;
                    //将附近地址渲染到对应位置
                    near_addList(nearPost);

                    province = nearPost.addressComponents.province;
                    city = nearPost.addressComponents.city;
                    area = isEmpty(nearPost.addressComponents.district)?'':nearPost.addressComponents.district;
                    getAddressCode(province,city,area);

                });
            }
        });
    };

    //定位失败直接调地图
    function showErr() {
        lat='30.462959';
        lng = '114.419449';
        //调用初始化函数地图
        //拿到经纬度并定位
        make_map(lat,lng);
    };


}

function make_map(lat,lng) {
    center = new qq.maps.LatLng(lat, lng);
    map.setCenter(center);
    marker = new qq.maps.Marker({
        map:map,
        position: center
    });
}

function codeLatLng(lat,lng) {
    //获取输入框的经纬度
    var latLng = new qq.maps.LatLng(lat, lng);
    //对指定经纬度进行解析
    geocoder.getAddress(latLng);
    //设置服务请求成功的回调函数
    geocoder.setComplete(function(result) {
        nearPost = result.detail;
        //将附近地址渲染到对应位置
        near_addList(nearPost);
    });
    //若服务请求失败，则运行以下函数
    geocoder.setError(function() {
        return null;
    });
}

function near_addList(near_post) {
    var html = template('choose-content',near_post);
    $('#choose').html(html);
    var list = near_post.nearPois;
    //选择所需的详情地址
    $('.address-choose').bind('click',function (e) {
        to_addDetail = 1;
        marker.setMap(null);
        /*info.setMap(null);*/
        var index = parseInt(this.getAttribute('data-index'));
        lat = list[index].latLng.lat;
        lng = list[index].latLng.lng;
        var user_add = list[index].latLng;

        //获取省市区
        var provice = near_post.addressComponents.province;
        var city = near_post.addressComponents.city;
        var district = isEmpty(near_post.addressComponents.district)?'':near_post.addressComponents.district;
        getAddressCode(provice ,city ,district);

        if(!$('#address-choose'+index).hasClass('active')){
            $('.address-choose').removeClass('active');
            $('#address-choose'+index).addClass('active');
        }

        make_map(lat,lng);
        name = list[index].name;
        area_position = lat +',' + lng;
    })
}

//根据省市区 获取对应编码
function getAddressCode(provice,city,area) {

    area_info = provice + ' '+ city
    if(!isEmpty(area)){
        area_info += ' '+area;
    }
    //将省市区放到对应区域
    var p_id='';
    var c_id='';
    var a_id='';
    if(isEmpty(cityData3) || cityData3.length <=0){
        return;
    }
    for(var i=0;i<cityData3.length;i++){
        var data = cityData3[i];
        if(data.text == provice){
            p_id = data.value
            $('#province').val(data.value);
            var children = data.children;
            if(!isEmpty(children) && children.length > 0){
                for(var j = 0;j<children.length;j++){
                    if(children[j].text == city){
                        c_id = children[j].value;
                        $('#city').val(children[j].value);
                        children = children[j].children;
                        if(!isEmpty(children) && children.length > 0){
                            for(var m =0;m<children.length;m++){
                                if(children[m].text == area){
                                    a_id = children[m].value;
                                    $('#area').val(children[m].value);
                                    break;
                                }else if(m >= children.length -1){
                                    $('#area').val(c_id);
                                }
                            }
                        }else {
                            $('#area').val(c_id);
                        }
                        break;
                    }else if(j >= children.length-1){
                        $('#city').val(p_id);
                        $('#area').val(p_id);
                    }
                }
            }else {
                $('#city').val(p_id);
                $('#area').val(p_id);
            }
            break;
        }
    }
}

$('#address').bind("input propertychange",function (event) {
    var info = $('#area_info').val() + $('#address').val();


    //地址和经纬度之间进行转换服务
    geocoder = new qq.maps.Geocoder({
        //设置服务请求成功的回调函数
        complete: function(result) {
            lat = result.detail.location.lat;
            lng = result.detail.location.lng;
            latLng = lat+','+lng;
            $('#shop_position').val(latLng);

            //调用初始化函数地图
            init();

        },
        //若服务请求失败，则运行以下函数
        error: function() {
            layer.msg('店铺地址定位出错，请在地图上自行选择');
        }
    });
    //如果没有经纬度 那么 按照店铺地址获取经纬度
    geocoder.getLocation(info);
})

$('#search_address').bind("input propertychange",function(event){
    var infos = $('.search_address').val();
    if(!isEmpty(infos)){

        $('.img_cuo').css('display','block');
        var url = 'https://apis.map.qq.com/ws/place/v1/suggestion/?region='+region+'&keyword='+infos+'&output=jsonp&key=RHHBZ-K26W6-CPISS-ENGXG-HVCRS-QJFQT';
        url = encodeURI(url);
        $.ajax({
            type:"get",
            url: url,
            dataType: "JSONP",
            jsonp: 'callback',
            success: function (res) {
                var search_nearPost = res.data;
                if(!isEmpty(search_nearPost) && search_nearPost.length >0){

                    var html = template('choose-content-search',res);
                    $('#choose_search').html(html);
                    $(function(){
                        $('.address-choose-search').bind('click',function (e) {
                            var list = search_nearPost;
                            /*to_addDetail = 1*/
                            if(!isEmpty(marker)){
                                marker.setMap(null);
                            }
                            $('#search').hide();
                            $('#latLng').hide();
                            $('#add').show();
                            var index = parseInt(this.getAttribute('data-index'));
                            lat = list[index].location.lat;
                            lng = list[index].location.lng;
                            //获取附近地址并赋值到列表中
                            codeLatLng(lat,lng);
                            area_position = lat+','+lng;
                            $('#shop_position').val(area_position);
                            //将对应地址和经纬度放到hidden中
                            //获取省市区
                            var provice = list[index].province;
                            var city = list[index].city;
                            var district = isEmpty(list[index].district)?'':list[index].district;
                            getAddressCode(provice,city,district);
                            area_info = provice + ' ' + city + ' '+district;
                            $('#area_info').val(area_info);
                            name = list[index].title;
                            $('#address').val(name);
                            make_map(lat,lng);
                            //清空搜索页的内容
                            $('#search_address').val('');
                            $('#choose_search').html('');

                        })
                    })
                }
            },
            error: function (res,reson) {
                mui.toast('请求失败');
            }
        });
        /*codeAddress(infos);*/
    }else {
        $('.img_cuo').css('display','none')
    }
})
var to_addDetail = 0;
//选完地址，点击完成
$('.choose_end').bind('click',function () {
    if(!to_addDetail){
        mui.toast('请在地址列表选择地址');
    }else {
        $('#area_info').val(area_info);
        $('#address').val(name);
        $('#shop_position').val(area_position);
        $('#latLng').hide();
        $('#add').show();
    }
})


